package curator;

import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.locks.InterProcessMutex;
import org.apache.curator.retry.ExponentialBackoffRetry;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

/**
 * Created by Lenovo on 2018/11/22.
 */
public class Lock1 {

    static final String CONNECTION_ADDR = "10.1.66.76:2181";
    //static final int CONNECTION_TIMEOUT = 1000;
    static final int SESSION_TIMEOUT = 5000;
    static int j = 0;
    static CuratorFramework curatorFramework = null;

    public static void main(String[] args) throws Exception{
        curatorFramework = create();
        curatorFramework.start();
        final InterProcessMutex lock = new InterProcessMutex(curatorFramework, "/lock");
        final CountDownLatch countDownLatch = new CountDownLatch(1);
        for(int i = 0; i<=10; i++){
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try{
                        countDownLatch.await();
                        if(lock.acquire(1, TimeUnit.SECONDS)) {
                            //lock.acquire();
                            //业务开始
                            String orderNum = GetOrder();
                            System.out.println((Thread.currentThread().getName() + "创建了订单号：【" + orderNum + "】！"));
                            //业务结束
                        }
                    }catch (Exception e){
                        e.printStackTrace();
                    }finally {
                        try {
                            lock.release();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }
            }).start();
            Thread.sleep(1000);
            countDownLatch.countDown();
        }
        close();
    }

    public static CuratorFramework create(){
        RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);
        curatorFramework = CuratorFrameworkFactory.builder()
                .connectString(CONNECTION_ADDR)
                //.connectionTimeoutMs(CONNECTION_TIMEOUT)
                .sessionTimeoutMs(SESSION_TIMEOUT)
                .retryPolicy(retryPolicy)
                .build();
        return curatorFramework;
    }

    public static void close(){
        curatorFramework.close();
    }

    public static String GetOrder(){
        j++;
        String ss= "NewOrder"+new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss-"+j).format(new Date());
        return ss;
    }
}


